from jwt import encode
from dotenv import load_dotenv
from pathlib import Path
from os import environ
from time import time
from .type import (
    Unit,
    Language
)

load_dotenv()
ROOT = Path(__file__).parent.parent
DATA = ROOT / 'data'
DOCS = ROOT / 'docs'

def generate_jwt(key_id: str, project_id: str, private_key: str) -> str:
    """
    ### Generate a JWT token for the QWeather API

    Args:
        key_id: The key ID of the private key
        project_id: The project ID of the QWeather API
        private_key: The private key of the QWeather API

    Returns:
        The JWT token
    """
    now = int(time())
    # JWT header and payload
    headers = {'kid': key_id}
    payload = {
        'sub': project_id,
        'iat': now - 30,
        'exp': now + 900
    }
    return encode(
        payload=payload,
        key=private_key,
        algorithm='EdDSA',
        headers=headers
    )

class Config:
    """### Weather configurations"""
    # Banner
    banner_path = DATA / 'banner.txt'
    with open(banner_path, 'r', encoding='utf-8') as f:
        banner = f.read()
    # City database
    city_csv = DATA / 'city.csv'
    city_db = DATA / 'city.db'
    # Private key
    private_key_path = DATA / 'ed25519-private.pem'
    with open(private_key_path, 'r', encoding='utf-8') as f:
        private_key = f.read()
    # QWeather API configurations
    base_url = environ['QWEATHER_BASE_URL']
    key_id = environ['QWEATHER_KEY_ID']
    project_id = environ['QWEATHER_PROJECT_ID']
    token = generate_jwt(key_id, project_id, private_key)
    languages: list[Language] = [
        'zh', 'zh-hans', 'zh-hant', 'en', 'de', 'es', 'fr', 'it', 'ja', 'ko',
        'ru', 'hi', 'th', 'ar', 'pt', 'bn', 'ms', 'nl', 'el', 'la', 'sv',
        'id', 'pl', 'tr', 'cs', 'et', 'vi', 'fil', 'fi', 'he', 'is', 'nb'
    ]
    language: Language = 'zh'
    units: list[Unit] = ['m', 'i']
    unit: Unit = 'm'
    console_width = 70

config = Config()
